<template>
  <div class="toolbar-container">
    <div class="toolbar-button-group">
      <el-button link type="primary" icon="el-icon-folder-opened" @click="handleOpen">
        打开
      </el-button>
      <el-button link type="primary" icon="el-icon-folder-add" @click="handleNew">
        新建工程
      </el-button>
      <el-button link type="primary" icon="el-icon-files" :disabled="!settings || !settings.projectPath"
        @click="handleSave">
        保存
      </el-button>
      <el-button link type="primary" icon="el-icon-view" :disabled="!settings || !settings.projectPath"
        @click="handlePreview">
        仿真
      </el-button>
      <el-button link type="primary" icon="el-icon-view" :disabled="!settings || !settings.projectPath"
        @click="handlePagePreview">
        页面仿真
      </el-button>
      <el-button link type="primary" icon="el-icon-document" title="系统代码" :disabled="!settings || !settings.projectPath"
        @click="handleEditCode">
        系统代码
      </el-button>
      <el-button link type="primary" icon="el-icon-download" :disabled="!settings || !settings.projectPath"
        @click="handleDownload">
        导出U盘
      </el-button>
    </div>
    <div class="toolbar-button-group">
      <el-button link type="primary" icon="el-icon-document-copy" :disabled="!designer || !designer.selectedWidget"
        @click="handleCopy">
        复制
      </el-button>
      <el-button link type="primary" icon="el-icon-document-copy" :disabled="!designer || !designer.selectedWidget"
        @click="handleCopyPage">
        整页复制
      </el-button>
      <el-button link type="primary" icon="el-icon-download" :disabled="!settings || !settings.projectPath"
        @click="handlePaste">
        粘贴
      </el-button>
    </div>
    <div class="toolbar-button-group">
      <el-button link type="primary" icon="el-icon-close-bold" :disabled="!designer || !designer.selectedWidget"
        @click="handleDelete">
        删除
      </el-button>
      <el-button link type="primary" :disabled="!settings || !settings.projectPath" @click="clearFormWidget">
        <svg-icon icon-class="el-delete" />
        {{ i18nt('designer.toolbar.clear') }}
      </el-button>
      <el-button link type="primary" :disabled="undoDisabled" :title="i18nt('designer.toolbar.undoHint')"
        @click="undoHistory">
        <svg-icon icon-class="undo" />
        {{ i18nt('designer.toolbar.undoHint') }}
      </el-button>
      <el-button link type="primary" :disabled="redoDisabled" :title="i18nt('designer.toolbar.redoHint')"
        @click="redoHistory">
        <svg-icon icon-class="redo" />
        {{ i18nt('designer.toolbar.redoHint') }}
      </el-button>
    </div>
    <div class="toolbar-button-group">
      <el-button link type="primary" icon="el-icon-tools" :disabled="!settings || !settings.projectPath"
        @click="handleSetting">
        系统设置
      </el-button>
      <el-button link type="primary" icon="el-icon-tools" :disabled="!settings || !settings.projectPath"
        @click="languSettingOpen">
        语言设置
      </el-button>
      <el-button link type="primary" :disabled="!settings || !settings.projectPath" @click="handleId">
        ID
      </el-button>
      <div class="zoom-group">
        <el-text class="zoom-text">{{ `${zoomValue}%` }}</el-text>
        <el-button link type="primary" icon="el-icon-minus" :disabled="!settings || !settings.projectPath"
          @click="handleMinusZoom"></el-button>
        <el-slider v-model="zoomValue" :min="50" :max="150" :step="1" :disabled="!settings || !settings.projectPath"
          size="small" :show-tooltip="false" @change="handleZoom" />
        <el-button link type="primary" icon="el-icon-plus" :disabled="!settings || !settings.projectPath"
          @click="handlePlusZoom"></el-button>
      </div>
    </div>
  </div>

  <el-dialog v-model="showSettingDialog" size="large" :title="settingDialogTitle" width="500">
    <el-form size="large">
      <el-form-item v-show="isNewProjiect" label="工程目录" :required="true">
        <el-input v-model="settingsForm.projectPath" placeholder="请选择工程目录" disabled>
          <template #suffix>
            <el-icon class="el-input__icon"
              :style="{ fontSize: '20px', marginLeft: 0, color: '#409eff', cursor: 'pointer' }"
              @click="handleOpenUserPath">
              <el-icon-folder-opened />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item v-show="isNewProjiect" label="屏幕尺寸" :required="true">
        <el-radio-group v-model="settingsForm.widthAndHeight">
          <el-radio-button label="1280*800" value="1280*800" />
          <el-radio-button label="1024*600" value="1024*600" />
          <el-radio-button label="800*480" value="800*480" />
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="false" label="软件大小" :required="true">
        <el-input-number v-model="settingsForm.scale" :min="0" :max="1000" :step="10" />
      </el-form-item>
      <el-form-item v-show="isNewProjiect" label="屏幕方向" :required="true">
        <el-radio-group v-model="settingsForm.screenOrientation">
          <el-radio-button label="0" :value="0" />
          <el-radio-button label="90" :value="1" />
          <el-radio-button label="180" :value="2" />
          <el-radio-button label="270" :value="3" />
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="!isNewProjiect" label="串口号" :required="true">
        <el-select v-model="settingsForm.serialPort" :loading="loadingPorts" placeholder="检测串口设备中..."
          @focus="loadSerialPorts">
          <el-option v-for="port in serialPortList" :key="port.value" :label="port.label" :value="port.value" />
          <el-option v-if="serialPortList.length === 0" disabled :value="null" label="未检测到串口设备" />
        </el-select>
      </el-form-item>

      <el-form-item v-show="!isNewProjiect" label="波特率" :required="true">
        <el-select v-model="settingsForm.baudRate">
          <el-option v-for="item in baudRateOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handlerSettingCancel">取消</el-button>
        <el-button v-if="isNewProjiect" type="primary" @click="handleNewProject">
          创建工程
        </el-button>
        <el-button v-else type="primary" @click="handlerSettingOK"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="showLanguDialog" title="设置语言" width="700">
    <el-form label-width="120px" class="demo-dynamic">
      <el-form-item label="语言 1">
        <el-input style="width: 450px" value="font_1.ttf" disabled />
      </el-form-item>
      <el-form-item v-for="(item, index) in languages" :label="'语言 ' + (index +2)" :key="item.text">
        <el-select v-model="item.value" placeholder="选择字体..." style="width: 240px">
          <el-option v-for="item2 in fontList" :key="item2.name" :label="item2.name" :value="item2.name">
            {{ item2.name }}
          </el-option>
          <el-option @click.prevent="removeDomain(item)">
            <span style="color: red">删除此语言</span>
          </el-option>
        </el-select>
        <el-input v-model="item.desc" placeholder="此语言描述" style="width: 200px;margin-left: 10px;" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="addDomain"> 增加语言 </el-button>
        <el-button @click="languSettingCancel">取消</el-button>
        <el-button type="primary" @click="languSettingOk"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="isExporting" title="导出项目" width="30%" :close-on-click-modal="false" :close-on-press-escape="false"
    :show-close="false" style="border-radius: 12px; background: #f5f5f5;">
    <div style="text-align: center; padding: 10px 20px;">
      <p
        style="font-size: 25px; margin-bottom: 15px; color: #409EFF; font-weight: 600;">
        正在导出，请稍候...</p>
    </div>
  </el-dialog>

  <el-dialog v-model="showExportSuccess" title="导出完成" width="30%" style="border-radius: 12px; background: #f5f5f5;">
    <div style="text-align: center; padding: 30px 20px;">
      <p
        style="font-size: 25px; margin-bottom: 15px; color: #409EFF; font-weight: 600; letter-spacing: 1px;">
        导出成功！</p>
    </div>
    <template #footer>
      <span class="dialog-footer"
        style="display: block; background: #f5f5f5; padding: 0px; text-align: center; border-radius: 0 0 12px 12px;">
        <el-button type="primary" @click="showExportSuccess = false"
          style="padding: 18px 30px; border-radius: 8px; font-weight: 550;">
          确 定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import * as ELECTRON from '@/electron'
import * as EVENTS from '../event'

const settingsInit = {
  projectPath: '',
  widthAndHeight: '1024*600',
  scale: 100,
  screenOrientation: 0,
  baudRate: 115200
}

const baudRateOptions = [
  { label: '300', value: 300 },
  { label: '600', value: 600 },
  { label: '1200', value: 1200 },
  { label: '2400', value: 2400 },
  { label: '4800', value: 4800 },
  { label: '9600', value: 9600 },
  { label: '14400', value: 14400 },
  { label: '19200', value: 19200 },
  { label: '38400', value: 38400 },
  { label: '56000', value: 56000 },
  { label: '57600', value: 57600 },
  { label: '115200', value: 115200 },
  { label: '128000', value: 128000 },
  { label: '256000', value: 256000 }
]

export default {
  name: 'ToolbarPanel',
  inject: ['getDesignerConfig'],
  props: {
    designer: Object,
    settings: Object
  },
  data() {
    return {
      isExporting: false,
      showExportSuccess: false,
      designerConfig: this.getDesignerConfig(),
      portCheckInterval: null,
      zoomValue: this.settings && this.settings.scale ? this.settings.scale : 100,
      isNewProjiect: false,
      showSettingDialog: false,
      settingsForm: { ...settingsInit },
      languages: [],
      fontList: [],
      showLanguDialog: false,
      baudRateOptions,
      serialPortList: [],
      loadingPorts: false
    }
  },
  computed: {
    settingDialogTitle() {
      return this.isNewProjiect ? '新建工程' : '设置'
    },
    undoDisabled() {
      if (!this.designer) {
        return true
      }
      return !this.designer.undoEnabled()
    },
    redoDisabled() {
      if (!this.designer) {
        return true
      }
      return !this.designer.redoEnabled()
    }
  },
  watch: {
    settings(value) {
      if (value) {
        const { width, height, scale, ...rest } = value
        this.zoomValue = scale
        this.settingsForm = {
          widthAndHeight: `${width}*${height}`,
          scale,
          ...rest
        }
        if (this.serialPortList.length === 0 && !this.loadingPorts) {
          this.loadSerialPorts()
        }
      } else {
        this.settingsForm = { ...settingsInit }
      }
    }
  },
  mounted() {
    this.loadSerialPorts()
    this.setupPortMonitoring()
    
    this.$emitter.on(ELECTRON.OPEN_USER_PATH_RESULT, (projectPath) => {
      this.settingsForm.projectPath = projectPath
    })

    this.$emitter.on(EVENTS.GET_FONT_RESOURCE_LIST_RESULT, (fontList) => {
      this.languages = []
      this.fontList = []
      fontList.forEach((key) => {
        this.fontList.push({ name: key })
      })

      let languages = this.settings.languages
      if (languages) {
        this.languages = languages
      }
    })
  },
  beforeUnmount() {
    this.cleanupPortMonitoring()
  },
  unmounted() {
    this.$emitter.off(ELECTRON.OPEN_USER_PATH_RESULT)
  },
  methods: {
    setupPortMonitoring() {
      if (window.electronAPI?.onSerialPortsUpdate) {
        window.electronAPI.onSerialPortsUpdate((ports) => {
          this.updatePortList(ports)
        })
      } else {
        this.portCheckInterval = setInterval(() => {
          this.loadSerialPorts()
        }, 2000)
      }
    },
    cleanupPortMonitoring() {
      if (window.electronAPI?.onSerialPortsUpdate) {
        window.electronAPI.onSerialPortsUpdate(null)
      }
      if (this.portCheckInterval) {
        clearInterval(this.portCheckInterval)
      }
    },
    updatePortList(ports) {
      if (ports.length > 0) {
        this.serialPortList = ports.map(p => ({
          value: p.path.match(/^COM(\d+)/i)[1],
          label: `${p.path}${p.manufacturer ? ` (${p.manufacturer})` : ''}`
        }))
        
        if (!this.serialPortList.some(p => p.value === this.settingsForm.serialPort)) {
          this.settingsForm.serialPort = null
        }
        
        if (!this.settingsForm.serialPort && this.serialPortList.length > 0) {
          this.settingsForm.serialPort = this.serialPortList[0].value
        }
      } else {
        this.serialPortList = [{
          value: '1',
          label: '未检测到串口设备(默认COM1)',
          disabled: true
        }]
        this.settingsForm.serialPort = '1'
      }
    },
    async loadSerialPorts() {
      try {
        const ports = await window.electronAPI.getSerialPorts()
        this.updatePortList(ports)
      } catch (error) {
        console.error('刷新串口列表失败:', error)
      }
    },
    handleOpen() {
      this.$emitter.emit(ELECTRON.OPEN_PROJECT)
    },
    handleNew() {
      this.newProject()
    },
    newProject() {
      this.isNewProjiect = true
      this.showSettingDialog = true
    },
    handleNewProject() {
      this.showSettingDialog = false
      const settings = this.getSettings()
      this.$emitter.emit(ELECTRON.INIT_WORKSPACE_SETTINGS, JSON.parse(JSON.stringify(settings)))
    },
    getSettings() {
      const { projectPath, widthAndHeight, ...rest } = this.settingsForm
      const size = widthAndHeight.split('*').map((str) => parseInt(str))

      return {
        ...rest,
        width: size[0],
        height: size[1],
        ...(this.isNewProjiect ? { projectPath } : {})
      }
    },
    handleOpenUserPath() {
      this.$emitter.emit(ELECTRON.OPEN_USER_PATH)
    },
    handleSave() {
  this.$emitter.emit(EVENTS.SAVE_ALL_CODE_TABS, {
    callback: () => {
      // 保存完成后不需要额外操作，因为已经在 saveAllUnsavedCodeTabs 中触发了保存
    }
  });
  this.$message.success('保存成功');
},
    handleCompile() {
      this.$emitter.emit(ELECTRON.EXPORT_LUA_SCRIPT)
    },
    handlePreview() {
    this.$emitter.emit(EVENTS.SAVE_ALL_CODE_TABS, {
      callback: () => {
        this.$emitter.emit(ELECTRON.CLEAR_DEBUG_LOG);
        this.$emitter.emit(ELECTRON.START_DEBUG);
      }
    });
  },
    handlePagePreview() {
    this.$emitter.emit(EVENTS.SAVE_ALL_CODE_TABS, {
      callback: () => {
        this.$emitter.emit(ELECTRON.CLEAR_DEBUG_LOG);
        this.$emitter.emit(
          ELECTRON.START_PAGE_DEBUG,
          (this.designer && this.designer.options.name) || ''
        );
      }
    });
  },
    handleEditCode() {
      this.$emitter.emit(EVENTS.OPEN_CODE_EDITOR)
    },
    async handleDownload() {
  if (!this.settings || !this.settings.projectPath) return;

  // 保存所有未保存的代码
  await new Promise((resolve) => {
    this.$emitter.emit(EVENTS.SAVE_ALL_CODE_TABS, {
      callback: () => {
        resolve();
      }
    });
  });

  try {
    const { canceled, filePaths } = await window.electronAPI.showOpenDialog({
      properties: ['openDirectory'],
    });
    if (canceled) return;
    const exportPath = filePaths[0];

    this.isExporting = true;
    await window.electronAPI.exportProject(exportPath);
    this.isExporting = false;
    this.showExportSuccess = true;
  } catch (error) {
    console.error('导出失败:', error);
    this.isExporting = false;
    this.$message.error('导出失败，请重试');
  }
},
    handleCopy() {
      if (this.designer && this.designer.selectedWidget) {
        this.designer.copySelectedWidget(this.designer.selectedWidget)
      }
    },
    handleCopyPage() {
      if (this.designer) {
        this.$confirm(`确定要复制 ${this.designer.options.name} 整个页面吗？`)
          .then(() => {
            this.$emitter.emit(EVENTS.COPY_PAGE, this.designer)
          })
          .catch(() => {})
      }
    },
    handlePaste() {
      if (this.designer) {
        this.designer.pasteWidget()
      }
    },
    deleteWidget(widget) {
      this.designer.deleteWidget(widget, this.designer.widgetList)
      return
    },
    handleDelete() {
      if (this.designer && this.designer.selectedWidget) {
        this.$confirm(`确定要删除 ${this.designer.selectedWidget.options.name} 组件吗？`)
          .then(() => {
            this.deleteWidget(this.designer.selectedWidget)
          })
          .catch(() => {})
      }
    },
    clearFormWidget() {
      this.$confirm('确定要清空页面的组件吗？')
        .then(() => {
          this.designer.clearDesigner()
          this.designer.formWidget.clearWidgetRefList()
        })
        .catch(() => {})
    },
    handleSetting() {
      this.$emitter.emit(EVENTS.OPEN_SETTING)
    },
    languSettingOpen() {
      this.$emitter.emit(EVENTS.GET_FONT_RESOURCE_LIST)
      this.$nextTick(() => {
        this.showLanguDialog = true
        console.log('langu', this.fontList)
      })
    },
    languSettingCancel() {
      this.showLanguDialog = false
    },
    languSettingOk() {
      this.settings.languages = this.languages
      this.handleSave();
      this.showLanguDialog = false
    },
    addDomain() {
      this.languages.push({
        value: '',
        desc: ''
      })
    },
    removeDomain(item) {
      var index = this.languages.indexOf(item)
      if (index !== -1) {
        this.languages.splice(index, 1)
      }
    },
    openSettingModal(isNewProjiect) {
      this.isNewProjiect = isNewProjiect
      this.showSettingDialog = true
      if (!isNewProjiect) {
        this.loadSerialPorts()
      }
    },
    handlerSettingCancel() {
      this.showSettingDialog = false
    },
    handlerSettingOK() {
      this.showSettingDialog = false
      const settings = this.getSettings()
      this.$emitter.emit(EVENTS.SAVE_SETTING, settings)
    },
    handleId() {
      if (this.designer) {
        this.designer.setShowWidgetId(!this.designer.showWidgetId)
      }
    },
    handleZoom(value) {
      this.settings.scale = this.zoomValue = value
      this.$nextTick(() => {
        this.handleSave()
      })
    },
    handlePlusZoom() {
      this.zoomValue += 1
      if (this.zoomValue > 150) {
        this.zoomValue = 150
      }
      this.settings.scale = this.zoomValue
      this.$nextTick(() => {
        this.handleSave()
      })
    },
    handleMinusZoom() {
      this.zoomValue -= 1
      if (this.zoomValue < 50) {
        this.zoomValue = 50
      }
      this.settings.scale = this.zoomValue
      this.$nextTick(() => {
        this.handleSave()
      })
    },
    showToolButton(configName) {
      if (this.designerConfig[configName] === undefined) {
        return true
      }
      return !!this.designerConfig[configName]
    },
    undoHistory() {
      this.designer.undoHistoryStep()
    },
    redoHistory() {
      this.designer.redoHistoryStep()
    }
  }
}
</script>

<style lang="scss" scoped>
/* 添加旋转动画 */
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 工具栏按钮背景色*/
$--toolbar-button-background: #e0eeff;
$--toolbar-button-hover-background: #ffeaa6;

/* 工具栏按钮鼠标滑过背景色*/

.toolbar-container {
  margin-top: 4px;
  font-size: 16px;

  :after {
    display: block;
    content: '';
    clear: both;
  }

  :deep(.el-button) {
    margin-left: 5px;
    color: $--app-font-color;

    &.is-disabled {
      color: $--app-disabled-font-color;
    }

    &:hover {
      background-color: $--toolbar-button-hover-background;
    }

    span {
      font-size: 14px;
    }
  }

  .toolbar-button-group {
    display: flex;
    float: left;
    height: 25px;
    line-height: 25px;
    margin-left: 5px;
    border-radius: 4px;
    border-bottom: #6f9dd9 1px solid;
    background-color: $--toolbar-button-background;

    .zoom-group {
      display: inline-flex;
      position: relative;
      width: 160px;

      .zoom-text {
        position: absolute;
        line-height: 24px;
        width: 40px;
        text-align: right;
      }

      .zoom-text + button {
        margin-left: 38px;
      }

      :deep(.el-slider__button-wrapper) {
        width: 24px;
        height: 24px;
        top: -7px;

        .el-slider__button {
          width: 12px;
          height: 12px;
        }
      }
    }
  }

  .el-button i {
    margin-right: 3px;
  }
}
.el-dialog {
  border-radius: 10px;
}

.el-dialog__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 15px 20px;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: bold;
}
</style>